from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import Qt
from client.pages.ChangePswdWin import *
from client.func.ClientHttp import change_password_post
from client.func.Encryption import md5


class ChangePswdPage(QMainWindow, Ui_ChangePswdWin):
    def __init__(self):
        super(ChangePswdPage, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.uid = ""
        self.info_label.setText("")

        self.old_pswd_text.setEchoMode(QtWidgets.QLineEdit.Password)
        self.new_pswd_text1.setEchoMode(QtWidgets.QLineEdit.Password)
        self.new_pswd_text2.setEchoMode(QtWidgets.QLineEdit.Password)

        self.eye_button1.pressed.connect(lambda: self.EyePressed(self.eye_button1.objectName()))
        self.eye_button2.pressed.connect(lambda: self.EyePressed(self.eye_button2.objectName()))
        self.eye_button3.pressed.connect(lambda: self.EyePressed(self.eye_button3.objectName()))
        self.eye_button1.released.connect(lambda: self.EyeRelease(self.eye_button1.objectName()))
        self.eye_button2.released.connect(lambda: self.EyeRelease(self.eye_button2.objectName()))
        self.eye_button3.released.connect(lambda: self.EyeRelease(self.eye_button3.objectName()))
        self.save_button.clicked.connect(self.OnChange)
        self.cancel_button.clicked.connect(self.OnClose)

    def check(self):
        if self.old_pswd_text.text() and self.new_pswd_text1.text() and self.new_pswd_text2.text():
            if self.new_pswd_text1.text() == self.new_pswd_text2.text():
                return True
            else:
                self.info_label.setText(u"两次密码不一致")
                return False
        else:
            self.info_label.setText(u"密码不能为空!")
            return False

    def OnChange(self):
        if self.check():
            _, info = change_password_post(self.uid, md5(self.old_pswd_text.text()), md5(self.new_pswd_text1.text()))
            self.info_label.setText(info)

    def OnClose(self):
        self.close()

    def EyePressed(self, name):
        if name == "eye_button1":
            self.old_pswd_text.setEchoMode(QtWidgets.QLineEdit.Normal)
        elif name == "eye_button2":
            self.new_pswd_text1.setEchoMode(QtWidgets.QLineEdit.Normal)
        else:
            self.new_pswd_text2.setEchoMode(QtWidgets.QLineEdit.Normal)

    def EyeRelease(self, name):
        if name == "eye_button1":
            self.old_pswd_text.setEchoMode(QtWidgets.QLineEdit.Password)
        elif name == "eye_button2":
            self.new_pswd_text1.setEchoMode(QtWidgets.QLineEdit.Password)
        else:
            self.new_pswd_text2.setEchoMode(QtWidgets.QLineEdit.Password)

